/**
 * Created by elewen on 2016/12/27.
 */
(function () {
    app.controller('appCtrl', ['$rootScope', '$scope', 'AuthService', '$state', 'toaster', 'CS', '$timeout', 'RESTService',
        function ($rootScope, $scope, AuthService, $state, toaster, CS, $timeout, RESTService) {
            $rootScope.nowStamp = $.now();
            $rootScope.today = (new Date(new Date().toLocaleDateString()).getTime()) / 1000;
            // console.log($rootScope.today);
            $rootScope.thisYear = Date.parse((new Date().getFullYear()) + '-01-01 00:00:00') / 1000;

            $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                console.log('current state info --- ', {
                    'event': event,
                    'toState': toState,
                    'toParams': toParams,
                    'fromState': fromState,
                    'fromParams': fromParams,
                    'toStateName': toState.name
                });
                $scope.beforeState = fromState;
                $scope.currentState = toState;
                if (fromState.name == 'app.rates.list' || fromState.name == 'app.signal.list') {
                    $scope.beforeState1 = fromState;
                }
            });

            $scope.$on('parStatus', function (e, d) {
                $scope.sta = d;
                // console.log($scope.sta);
            });

            var _access_token = AuthService.loadData("_access_token");
            var _local_time = AuthService.loadData("_local_time");
            var _expires_in = AuthService.loadData("_expires_in");
            var isAuthenticated = ( $rootScope.nowStamp - _local_time > _expires_in * 1000 ) ? false : true;

            if (_access_token && isAuthenticated) {
                RESTService.getResponse('/rest/chatmessage/getUnreadCount?').then(function (response) {
                    console.log(response.data[0]);
                    $scope.count = response.data[0].count;
                });
            } else {
                $state.go('app.login');
                console.log('123456789');
            }

            var websocket = null;
            var connecting = null;

            function connectWs() {
                websocket = null;
                $timeout.cancel(connecting);
                connecting = $timeout(function () {
                    ws();
                }, 10000);
            }

            ws();
            function ws() {
                _access_token = AuthService.loadData("_access_token");
                if (window.WebSocket) {
                    console.log('该浏览器支持WebSocket');
                    websocket = new WebSocket(CS.url + "access_token=" + _access_token);
                    websocket.onopen = function (e) {
                        console.log("连接成功", e.target);
                    };
                    websocket.onmessage = function (event) {
                        // console.log("收到消息",event);
                        onMessage(event);
                    };
                    websocket.onerror = function (event) {
                        console.log("连接错误", event);
                        connectWs()
                    };
                    websocket.onclose = function (event) {
                        console.log("关闭连接", event);
                        connectWs()
                    };
                } else {
                    console.log("这个浏览器不支持WebSocket");
                }
            }

            function onMessage(event) {
                var data = JSON.parse(event.data);
                if (data.cnContent) {
                    // console.log($scope.currentState, $scope.count, $scope.sta);
                    // 在信号页面
                    if ($scope.currentState.name == 'app.signal.list') {
                        if ((data._instrument.followed == true && $scope.sta == 'followed') || $scope.sta == 'all') {
                            $timeout(function () {
                                console.log('收到新消息', data);
                                $scope.$broadcast('childMsgs', data);
                                $timeout(function () {
                                    $(document).scrollTop($('.msgslist')[0].scrollHeight);
                                }, 59);
                            });
                            //     $scope.$apply();
                        } else {
                            return;
                        }
                    } else {
                        if (data._instrument.followed == true) {
                            // 显示未读+1
                            $timeout(function () {
                                $scope.count += 1;
                                // console.log($scope.count);
                            });

                            // $scope.$apply();
                        } else {
                            return;
                        }
                    }

                } else {
                    console.log('当前上线：', data);
                }
            }

            window.onunload = function () {
                if (null != websocket) {
                    websocket.close();
                }
            };

        }])
        .controller('loginCtrl', ['$rootScope', '$scope', 'AuthService', '$state', 'toaster', function ($rootScope, $scope, AuthService, $state, toaster) {
            // start 上线后删除该代码
            $scope._name = AuthService.loadData('_name');
            $scope._pwd = AuthService.loadData('_pwd');
            console.log($scope._name, $scope._pwd);
            // end 上线后删除该代码

            $scope.login = function (name, pwd) {
                console.log(name, pwd);
                AuthService.login(encodeURI(name), pwd).then(
                    function (suc) {
                        AuthService.storeData('_name', name);
                        AuthService.storeData('_pwd', pwd);
                        $rootScope.user = AuthService.getLoginfo();
                        $state.go('app.rates.list');
                    }, function (err) {
                        toaster.pop('error', null, '用户名或密码错误', 1000);
                    }
                );
            }
        }])
        .controller('signUpCtrl', ['$scope', '$interval', 'RESTService', 'toaster', '$timeout', '$state', function ($scope, $interval, RESTService, toaster, $timeout, $state) {
            $scope.leftTime = -1;

            $scope.countdown = function () {
                RESTService.getResponse('/rest/user/checkUserName?userName=' + $scope._user.phoneNumber).then(function (res) {
                    if (res.data[0].exists) {
                        toaster.pop('error', null, res.message, 3000);
                        return;
                    }
                    RESTService.getResponse('/rest/smscode/sendSmsCode?userName=' + $scope._user.phoneNumber).then(function (res) {
                        if (res.code != 0) {
                            toaster.pop('error', null, res.message, 3000);
                        }
                    })
                });
                $scope.leftTime = 60;
                var clock = $interval(function () {
                    if ($scope.leftTime < 0) {
                        $interval.cancel(clock);
                    }
                    --$scope.leftTime;
                }, 1000);
            }

            $scope.signUp = function (userInfo) {
                if (userInfo.password === userInfo.rePassword && userInfo.agree == true && userInfo.phoneNumber.length == 11 && userInfo.verificationCode.length == 4) {
                    RESTService.getResponse('/rest/user/createUser?userName=' + userInfo.phoneNumber + '&password=' + userInfo.password + '&smsCode=' + userInfo.verificationCode).then(function (res) {
                        $scope._user = {};
                        if(res.code != 0){
                            toaster.pop('error', null, res.message, 3000);
                            return;
                        }

                        toaster.pop('success', null, '注册成功！3s 钟后自动跳转到登录页面', 3000);
                        $timeout(function(){
                            $state.go('app.login');
                        }, 3000);
                    });
                }
            }
        }])
        .controller('resetPwdCtrl', ['$scope', 'RESTService', '$interval', 'toaster' , '$timeout', function($scope, RESTService, $interval, toaster, $timeout){
            console.log(123, window);
            $scope.leftTime = -1;

            $scope.countdown = function () {
                RESTService.getResponse('/rest/user/checkUserName?userName=' + $scope._user.phoneNumber).then(function (res) {
                    if (!res.data[0].exists) {
                        toaster.pop('error', null, '该手机号暂未注册！', 3000);
                        return;
                    }
                    RESTService.getResponse('/rest/smscode/sendSmsCode?userName=' + $scope._user.phoneNumber).then(function (res) {
                        if (res.code != 0) {
                            toaster.pop('error', null, res.message, 3000);
                        }
                    })
                });
                $scope.leftTime = 2;
                var clock = $interval(function () {
                    if ($scope.leftTime < 0) {
                        $interval.cancel(clock);
                    }
                    --$scope.leftTime;
                }, 1000);
            }

            $scope.resetPwd = function (userInfo) {
                if (userInfo.password === userInfo.rePassword && userInfo.phoneNumber.length == 11 && userInfo.verificationCode.length == 4) {
                    RESTService.getResponse('/rest/user/resetPassword?userName=' + userInfo.phoneNumber + '&newPassword=' + userInfo.password + '&smsCode=' + userInfo.verificationCode).then(function (res) {
                        $scope._user = {};
                        if(res.code != 0){
                            toaster.pop('error', null, res.message, 3000);
                            return;
                        }

                        toaster.pop('success', null, '密码成功找回！3s 钟后自动跳转到登录页面', 3000);
                        $timeout(function(){
                            $state.go('app.login');
                        }, 3000);
                    });
                }
            }

        }])
})();